package service

import (
	"errors"

	"gitee.com/cyanbleeze/go-image-management/internal/model"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
)

type CreateFavoriteRequest struct {
	Name string `json:"name,omitempty" binding:"required,min=2"`
	Desc string `json:"desc,omitempty" binding:"omitempty,min=2"`
}

type FavoriteRequest struct {
	ID uint `json:"id,omitempty" binding:"required,min=1"`
}

type UpdateFavoriteRequest struct {
	ID   uint   `json:"id,omitempty" binding:"required,min=1"`
	Name string `json:"name,omitempty" binding:"required,min=2,max=30"`
	Desc string `json:"desc,omitempty" binding:"omitempty,min=2,max=255"`
}

type DeleteFavoriteRequest struct {
	ID uint `json:"id" binding:"required,min=1"`
}

func (svc *Service) CreateFavorite(params *CreateFavoriteRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	return svc.dao.CreateFavorite(
		params.Name,
		params.Desc,
		userID.(uint),
	)
}

func (svc *Service) UpdateFavorite(params *UpdateFavoriteRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	_, err := svc.dao.GetFavorite(
		params.ID,
		userID.(uint),
	)
	if err != nil {
		return errors.New("收藏夹不存在")
	}
	return svc.dao.UpdateFavorite(
		params.ID,
		params.Name,
		params.Desc,
	)
}

func (svc *Service) DeleteFavorite(params *DeleteFavoriteRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	_, err := svc.dao.GetFavorite(
		params.ID,
		userID.(uint),
	)
	if err != nil {
		return errors.New("收藏夹不存在")
	}
	return svc.dao.DeleteFavorite(
		params.ID,
	)
}

func (svc *Service) GetFavoriteList(pager *app.Pager) ([]*model.Favorite, int, error) {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return nil, 0, errors.New("登录用户信息不存在")
	}
	favoriteCount, err := svc.dao.CountFavoriteListByUID(userID.(uint))
	if err != nil {
		return nil, 0, err
	}
	favoriteList, err := svc.dao.GetFavoriteList(
		userID.(uint),
		pager.Page,
		pager.PageSize,
	)
	if err != nil {
		return nil, 0, err
	}
	return favoriteList, favoriteCount, nil
}
